package com.genius.adminmanager.group.service.impl;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.group.entity.GroupEntity;
import com.genius.adminmanager.group.service.GroupServiceAdapter;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.menu.service.MenuUtils;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.other.entity.SessionJson;
import com.genius.adminmanager.other.entity.TreeJson;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.TreeUtils;

@Service("groupSelectService")
public class GroupSelectServiceImpl extends GroupServiceAdapter{

	
	@Override
	public JSONObject getSelectHead(JSONObject json, HttpSession session, JSONObject response) {
		
		String menuId = json.getString(MenuJson.menuId);
    	
    	String roleId = (String)session.getAttribute(SessionJson.roleId);
		if(roleId == null){
    		response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Session_Failure);
    		return response;
    	}
//		String[] roleIdsArr = GeniusJsonUtil.getFieldByDouHaoArr(jiaoList, RoleJson.roleId);
    	
		response = MenuUtils.getPowerFileByMenu(roleId,menuId, response);
    	JSONObject result =  response.getJSONObject(ResponseJson.data);
    	if(result ==null){
    		response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
    		return response;
    	}
		return response;
	}

	@Override
	public JSONObject getSelectBody(JSONObject json, JSONObject response) {
		String table = "t_group";
    	String headField = json.getString(PageResult.headField)+",(select GROUP_CONCAT(concat(userId,'-',name))"
    			+" from t_user where find_in_set(t_group.groupId,groupId))users";
    	String idValue = json.getString(TreeJson.pid);
    	try {
        	JSONArray arr = TreeUtils.getOnceTree(GroupEntity.groupId, idValue, headField, table);
//        	System.out.println(arr);
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, arr);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, "查询菜单出错");
		}
		return response;
	}

	
}
